package com.heny.nc.service;

import com.heny.demo.common.CommonErrorCode;
import com.heny.demo.common.CommonException;
import com.heny.nc.model.NCModel;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author litao.cc
 * @version ExlProcessor.java v0.1 t2025/4/26 18:46
 * @date 2025/4/26 18:46
 * @description 存为exl
 */
public class ExlProcessor extends AbstractSaveDataProcessor {
    @Override
    public List<String> save(Map<Integer, List<NCModel>> data, String path, String baseFileName) {
        System.out.println("ExlProcessor start");

        List<String> pathList = new ArrayList<>(data.size());


        data.forEach((key, value) -> {
            String outputPath = buildSavePath(path, baseFileName, String.valueOf(key), "xlsx");
            try (Workbook workbook = new XSSFWorkbook();
                 FileOutputStream out = new FileOutputStream(outputPath)) {


                Sheet sheet = workbook.createSheet("Data");

                for (int rowNum = 0; rowNum < value.size(); rowNum++) {
                    NCModel item = value.get(rowNum);
                    String latString = item.getLatString();
                    String lonString = item.getLonString();
                    String dataString = item.getDataString();
                    Row row = sheet.createRow(rowNum);
                    row.createCell(0).setCellValue(latString);
                    row.createCell(1).setCellValue(lonString);
                    row.createCell(2).setCellValue(dataString);
                }
                // 自动调整列宽
                sheet.autoSizeColumn(0);
                sheet.autoSizeColumn(1);
                sheet.autoSizeColumn(2);
                workbook.write(out);
            } catch (Exception e) {
                throw new CommonException(CommonErrorCode.FILE_SYS_ERROR, "写入文件出现异常");
            }
            pathList.add(outputPath);
        });

        return pathList;
    }
}
